package com.wyp.didishige.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.wyp.didishige.R;
import com.wyp.didishige.config.BmobConstants;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.model.QQUser;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.PreferenceHelper;
import com.wyp.didishige.utils.SystemTool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.im.util.BmobLog;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**

 */
public class LoginActivity extends BaseActivity implements OnClickListener {

    UMSocialService mController = UMServiceFactory.getUMSocialService("com.wyp.com.wyp.didishige");

    EditText et_username, et_password;
    /**
     * 登录
     */
    Button btn_login;
    /**
     * 注册帐号
     */
    TextView register;
    TextView reset_pwd;
    ImageView mQQ = null;
    MyBroadcastReceiver myBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BmobConstants.ACTION_REGISTER_SUCCESS_FINISH);
        registerReceiver(myBroadcastReceiver, filter);
        addQQ();
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        register = (TextView) findViewById(R.id.btn_register);
        reset_pwd = (TextView) findViewById(R.id.reset_pwd);
        mQQ = (ImageView) findViewById(R.id.mQQ);
    }


    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        btn_login.setOnClickListener(this);
        register.setOnClickListener(this);
        reset_pwd.setOnClickListener(this);
        mQQ.setOnClickListener(this);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && BmobConstants.ACTION_REGISTER_SUCCESS_FINISH.equals(intent.getAction())) {
                finish();
            }
        }

    }

    @Override
    public void onClick(View v) {
        boolean isNetConnected = SystemTool.checkNet(this);
        if (!isNetConnected) {
            ShowToast(R.string.network_tips);
            return;
        }
        switch (v.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_register:
                IntentUtil.start_activity(this, RegisterActivity.class);
                break;
            case R.id.reset_pwd:
                IntentUtil.start_activity(this, ResetPswActivity.class);
                break;
            case R.id.mQQ:
                login(SHARE_MEDIA.QQ);
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 登录
     */
    private void login() {
        String name = et_username.getText().toString();
        String password = et_password.getText().toString();

        if (TextUtils.isEmpty(name)) {
            ShowToast(R.string.toast_error_username_null);
            return;
        }

        if (TextUtils.isEmpty(password)) {
            ShowToast(R.string.toast_error_password_null);
            return;
        }

        login(name, password);
    }

    private void gotoMain() {
        User user = userManager.getCurrentUser(User.class);
        if (user.getSex()) {
            PreferenceHelper.write(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, true);
        } else {
            PreferenceHelper.write(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false);
        }
        IntentUtil.start_activity(LoginActivity.this, MainActivity.class);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    /**
     * 添加qq
     */
    private void addQQ() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, Config.QQ_APP_ID, Config.QQ_APP_key);
        umqqSsoHandler.addToSocialSDK();
    }

    /**
     * 授权。如果授权成功，则获取用户信息</br>
     */
    private void login(final SHARE_MEDIA platform) {
        mController.doOauthVerify(this, platform, new SocializeListeners.UMAuthListener() {

            @Override
            public void onStart(SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "start", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "onComplete", Toast.LENGTH_SHORT).show();
                String uid = value.getString("uid");
                chackIsRegister(uid, platform);
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
            }
        });
    }

    /**
     * 检查用户是否注册
     *
     * @param uid
     */
    private void chackIsRegister(final String uid, final SHARE_MEDIA platform) {
        userManager.queryUserByName(uid, new FindListener<BmobChatUser>() {
            @Override
            public void onSuccess(List<BmobChatUser> list) {
                if (list != null && list.size() > 0) {
                    login(uid, uid);
                } else {
                    //获取QQ资料后跳转注册
                    if (!TextUtils.isEmpty(uid)) {
                        getUserInfo(platform,uid);
                    } else {
                        Toast.makeText(LoginActivity.this, "授权失败...", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    private void login(String name, String pwd) {
        loading.setMessage("正在登陆...");
        loading.setCanceledOnTouchOutside(false);
        loading.show();
        User user = new User();
        user.setUsername(name);
        user.setPassword(pwd);

        user.setLastLogin(System.currentTimeMillis());

        userManager.login(user, new SaveListener() {

            @Override
            public void onSuccess() {
                loading.dismiss();
                //更新用户的地理位置以及好友的资料
                updateUserInfos();
                gotoMain();
            }

            @Override
            public void onFailure(int errorcode, String arg0) {
                loading.cancel();
                BmobLog.i(arg0);
                if (errorcode==101){
                    ShowToast("用户名或密码错误");
                }else{
                    ShowToast(arg0);
                }

            }
        });
    }

    /**
     * 获取授权平台的用户信息</br>
     */
    private void getUserInfo(SHARE_MEDIA platform,final String uid) {
        mController.getPlatformInfo(this, platform, new SocializeListeners.UMDataListener() {

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {

                if (info != null) {
                    String userIf = info.toString();
                    QQUser user = new QQUser();
                    user.setUid(uid);
                    user.setScreen_name(info.get("screen_name").toString());
                    user.setGender(info.get("gender").toString());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Config.KEY_USER, user);
                    IntentUtil.start_activity(LoginActivity.this, RegisterQQActivity.class, bundle);
                }
            }
        });
    }
}
